// 更换服务器ip
const requestIp = "http://192.168.1.50:8080"
// const requestIp = "http://127.0.0.1:8080"

window.onload = function () {
    // 获取接口
    listData();

    axios.get(requestIp + "/getTableName")
        .then(res => {
            // console.log("上传结果: " + res.data)
            selectTable(res.data)
        })
}

function listData(tableName) {
    getTable(tableName).then(res => {
        initTb(res.tableName, res.head, res.body);
    });
}

function importTable() {
    let dialog = document.getElementById("dialogView");
    dialog.style.display = 'block'
}

function unImport() {
    let dialog = document.getElementById("dialogView");
    dialog.style.display = 'none'

    clearValue(["result", "upload", "tabName"])
}

function exportTable() {
    let select = document.getElementById("currentName");
    let index = select.selectedIndex;
    let tableName = select.options[index].value;
    if (tableName) {
        axios.get(requestIp + "/page", {params: {"tableName": tableName}})
            .then(res => {
                // [["1","晓敏","ok","12","2024/3/25","2024/3/25","2024/3/26"],["2","晓敏2","ok","null","null","null","null"]]}
                console.log("获取: " + JSON.stringify(res.data))
                let body = res.data.head.join(",") + "\n"
                let array = res.data.body;
                for (let i = 0; i < array.length; i++) {
                    for (let j = 0; j < array[i].length; j++) {
                        body += array[i][j] + "\t,";
                    }
                    body += "\n"
                }
                // console.log("数据: " + body)
                const uri = 'data:text/xlsx;charset=utf-8,\ufeff' + encodeURIComponent(body);
                // 通过创建a标签实现
                const link = document.createElement("a");
                link.href = uri;
                // 对下载的文件命名
                link.download = tableName + "-数据导出-" + new Date().toLocaleDateString() + ".xlsx";
                link.click();
            })
    } else {
        alert("未选中")
    }
}


function getFile() {
    document.getElementById("upload").click()
}


function selectFile() {
    let fileName = document.getElementById("upload").value;
    // 截取文件名称
    let split = fileName.split("\\");
    let finalName = split[split.length - 1];
    // 显示文件
    document.getElementById("result").innerText = finalName;
}

async function uploadFile() {
    let upload = document.getElementById("upload");
    let tableNameIn = document.getElementById("tabName");
    let fileName = upload.files;
    let tableName = tableNameIn.value;
    let formData = new FormData();
    if (fileName[0]) {
        formData.append("file", fileName[0])
        formData.append("tableName", tableName)
        await axios.post(requestIp + "/uploadFile", formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            cache: 'false'
        }).then(res => {
            alert("上传成功")
            clearValue(["result", "upload", "tabName"])
            initTb(res.data.tableName, res.data.head, res.data.body)
            let select = document.getElementById("currentName");
            let options = select.options;
            for (let i = 0; i < options.length; i++) {
                if (options[i].value === res.data.tableName) {
                    options[i].selected = true;
                    break;
                }
            }

            setTimeout(() => {
                let dialog = document.getElementById("dialogView");
                dialog.style.display = 'none';
            }, 1000)
        }).catch(error => {
            clearValue(["result", "upload", "tabName"])
            alert("上传失败: " + error.data)
        })
    } else {
        alert("请选择导入的文件")
    }
}

function clearValue(ids) {
    for (let i = 0; i < ids.length; i++) {
        document.getElementById(ids[i]).value = ""
        document.getElementById(ids[i]).innerText = ""
    }

}

async function getTable(tableName) {
    let data;
    await axios.get(requestIp + "/page", {params: {"tableName": tableName}}).then(res => {
        data = res.data;
        // console.log("数据:" + JSON.stringify(data));
    }).catch(error => {
        // alert("上传失败: " + error.data)
    })
    return data;
}

function initTb(tableName, headName, bodyArray) {
    // console.log("表头:" + JSON.stringify(headName))
    let table = document.getElementById("tb");
    table.innerHTML = ""
    // 创建头部
    let thead = document.createElement("thead");

    // 生成头部
    let trH = document.createElement("tr");
    let rowLen = headName.length;
    for (let i = 0; i < rowLen; i++) {
        let tH = document.createElement("th");
        tH.innerHTML = headName[i]
        trH.append(tH)
    }
    thead.append(trH)
    table.append(thead)

    // console.log("数据:" + JSON.stringify(bodyArray))
    // [["1","晓敏","ok"],["2","晓敏2","ok"]]
    //创建内容
    let tbody = document.createElement("tbody");
    for (let i = 0; i < bodyArray.length; i++) {
        let trb = document.createElement("tr");
        for (let j = 0; j < rowLen; j++) {
            let td = document.createElement("td");
            let data = bodyArray[i][j];
            td.innerHTML = data === null || data === "null" ? "" : data
            trb.append(td)
        }
        tbody.append(trb)
    }
    table.append(tbody)

    selectTable(tableName)

}

function selectTable(tableName) {
    // 获取所有下拉值, 创建子选项, 拼接
    let select = document.getElementById("currentName");
    if (tableName !== undefined && tableName !== "") {
        if (typeof tableName === 'string') {

            // 如果存在则直接选择
            let create = Boolean(true);
            let options = select.options;
            for (let i = 0; i < options.length; i++) {
                if (options[i].value === tableName) {
                    options[i].selected = true;
                    create = false;
                    break
                }
            }
            if (create) {
                let option = document.createElement("option");
                option.innerHTML = tableName;
                select.append(option)
            }
        } else if (tableName instanceof Array) {
            // 拉取全部表名
            for (let i = 0; i < tableName.length; i++) {
                let option = document.createElement("option");
                option.innerHTML = tableName[i];
                select.append(option)
            }
        }
    } else {
        // 渲染表
        let index = select.selectedIndex;
        let value = select.options[index].value;
        listData(value)
        // 生成分页

        // alert("select: " + value)
    }
}